package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        // 调用mapper获取数据
        List<GoodsSalesDTO> goodsSalesDTOList =  orderMapper.selectSalesTop10(begin,end);
        // 遍历结果集，把名字存储到列表，把份数存到列表
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goods:goodsSalesDTOList){
            nameList.add(goods.getName());
            numberList.add(goods.getNumber());
        }

        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        return salesTop10ReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // 把日期期间的每一天存入列表
        List<LocalDate> localDateList = new ArrayList<>();
        while (! begin.equals(end)) {
            localDateList.add(begin);
            begin = begin.plusDays(1);
        }
        // 存入最后一天
        localDateList.add(end);

        List<Long> orderList = new ArrayList<>();
        List<Long> validCountList = new ArrayList<>();
        Long totalCount = 0l;
        Long validCount = 0l;
        // 遍历日期，求出每天新增人数和累计用户总数
        for (LocalDate localDate : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            // 获得每天新增人数
            Long validOrderCount  = getOrdersStatis(beginTime, endTime, Orders.COMPLETED);
            // 获得累计总用户
            Long totalOrderCount  = getOrdersStatis(beginTime, endTime, null);

            // 累计有效订单
            totalCount += totalOrderCount;
            validCount += validOrderCount;

            // 添加到数组
            orderList.add(totalOrderCount);
            validCountList.add(validOrderCount);
        }


        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(localDateList, ","));
        orderReportVO.setOrderCountList(StringUtils.join(orderList, ","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validCountList, ","));
        orderReportVO.setTotalOrderCount(totalCount.intValue());
        orderReportVO.setValidOrderCount(validCount.intValue());
        double d = 1.0*validCount/totalCount;
        orderReportVO.setOrderCompletionRate(d);
        return orderReportVO;
    }
    /**
     * 订单统计公共业务
     * @param beginTime
     * @param endTime
     * @param completed
     * @return
     */
    private Long getOrdersStatis(LocalDateTime beginTime, LocalDateTime endTime, Integer completed) {
        HashMap qurayParam = new HashMap();
        qurayParam.put("beginTime", beginTime);
        qurayParam.put("endTime", endTime);
        qurayParam.put("status", completed);
        Long userCount = userMapper.selectCount(qurayParam);
        return userCount != null ? userCount : 0;
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUsersStatistics(LocalDate begin, LocalDate end) {
        // 把日期期间的每一天存入列表
        List<LocalDate> localDateList = new ArrayList<>();
        while (! begin.equals(end)) {
            localDateList.add(begin);
            begin = begin.plusDays(1);
        }
        // 存入最后一天
        localDateList.add(end);

        List<Long> newUserList = new ArrayList<>();
        List<Long> totalUserList = new ArrayList<>();
        // 遍历日期，求出每天新增人数和累计用户总数
        for (LocalDate localDate : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            // 获得每天新增人数
            Long newUserCount = getUsersStatis(beginTime, endTime);

            // 获得累计总用户
            Long totalUserCount = getUsersStatis(null, endTime);

            // 添加到数组
            newUserList.add(newUserCount);
            totalUserList.add(totalUserCount);
        }

        // 返回需要的字符串
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(localDateList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        return userReportVO;
    }

    private Long getUsersStatis(LocalDateTime beginTime, LocalDateTime endTime) {
        HashMap qurayParam = new HashMap();
        qurayParam.put("beginTime", beginTime);
        qurayParam.put("endTime", endTime);
        Long userCount = userMapper.selectCountByMap(qurayParam);
        if (userCount == null) {
            userCount = 0l;
        }
        return userCount;
    }


    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        String dateList = "";
        String trunoverList = "";
        // 把日期区间中的每一天春入到列表里
        // 新建一个集合
        List<LocalDate> dateArrayList = new ArrayList<>();
        // 如果开始日期不等于结束日期，存入列表
        while (! begin.equals(end)) {
            dateArrayList.add(begin);
            // 下一天
            begin = begin.plusDays(1);
        }
        // 把最后一天加入列表
        dateArrayList.add(end);
        // 使用StringUtils.join工具类把集合转成字符串
        dateList = StringUtils.join(dateArrayList, ",");
        log.info("[日期列表] {}",dateList);
        dateList = dateList.replaceAll(LocalDate.now().getYear()+"-","");
        log.info("[日期列表] 修订后:{}",dateList);

        // 创建每天营业额列表
        List<Double> salesList = new ArrayList();
        // 遍历日期，拿到每一天的营业额
        for (LocalDate localDate : dateArrayList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 调用mapper查询，根据状态起/始日期查询
            // 创建一个查询列表，存入查询的数据
            HashMap hashMap = new HashMap();
            hashMap.put("status", Orders.COMPLETED);
            hashMap.put("beginTime", beginTime);
            hashMap.put("endTime", endTime);
            Double oneDayTurnover = orderMapper.selectByMap(hashMap);
            if (oneDayTurnover == null) {
                oneDayTurnover = 0d;
            }
            // 存入列表
            salesList.add(oneDayTurnover);
        }
        trunoverList = StringUtils.join(salesList,",");
        log.info("[营业额列表] {}",trunoverList);
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(trunoverList);
        return turnoverReportVO;
    }
}
